﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using KursnaListaPhoneLib.Services;
using KursnaListaPhoneLib.Storage;
using MSC.Phone.Common.Networking;
using Microsoft.Phone.Scheduler;
using Microsoft.Phone.Shell;

namespace KursnaListaPhoneAppScheduledTaskAgent
{
    public class ScheduledAgent : ScheduledTaskAgent
    {
        /// <remarks>
        /// ScheduledAgent constructor, initializes the UnhandledException handler
        /// </remarks>
        static ScheduledAgent()
        {
            // Subscribe to the managed exception handler
            Deployment.Current.Dispatcher.BeginInvoke(delegate
            {
                Application.Current.UnhandledException += UnhandledException;
            });
        }

        /// Code to execute on Unhandled Exceptions
        private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                Debugger.Break();
            }
        }

        private const string BaseUrl = "http://kursnalistamob.azurewebsites.net/";

        private static IHttpClient httpClient = null;
        public static IHttpClient HttpClient
        {
            get
            {
                if (httpClient == null)
                    httpClient = new HttpClient(BaseUrl);

                return httpClient;
            }
        }

        private static IKursnaListaStore store = null;

        public static IKursnaListaStore Store
        {
            get
            {
                if (store == null)
                {
                    store = new KursnaListaStore();
                }

                return store;
            }
        }

        private static IKursnaListaClient client = null;

        public static IKursnaListaClient Client
        {
            get
            {
                if (client == null)
                    client = new KursnaListaClient(HttpClient, Store);

                return client;
            }
        }

        /// <summary>
        /// Agent that runs a scheduled task
        /// </summary>
        /// <param name="task">
        /// The invoked task
        /// </param>
        /// <remarks>
        /// This method is called when a periodic or resource intensive task is invoked
        /// </remarks>
        protected override async void OnInvoke(ScheduledTask task)
        {
            var mainTile = ShellTile.ActiveTiles.FirstOrDefault();

            if (null != mainTile)
            {
                if (await Store.KursnaListaZaDaneNeedsUpdate())
                {
                    var result = await Client.UpdateKursnaListaZaDane(30);
                }
                var kursnaListaZaDane = await Store.GetKursnaListaZaDane();

                if (kursnaListaZaDane.Count > 0)
                {
                    var kursnaListaZaDan = kursnaListaZaDane.Last();

                    var backContent = new List<string>();
                    foreach (var stavkaKursneListe in kursnaListaZaDan.ZaEfektivniStraniNovac)
                    {
                        backContent.Add(string.Format("{0} {1:0.0000}", stavkaKursneListe.OznakaValute,
                                                      kursnaListaZaDan.SrednjiKurs.First(
                                                          k => k.OznakaValute == stavkaKursneListe.OznakaValute)
                                                                      .SrednjiKurs));
                    }

                    var tileData = new FlipTileData
                                       {
                                           BackContent = string.Join("\n", backContent),
                                           BackTitle = kursnaListaZaDan.Datum.ToShortDateString()
                                       };

                    mainTile.Update(tileData);
                }
            }

            NotifyComplete();
        }
    }
}